import axios from "axios";
import { Error,Response } from "@/types/result";
import {guid} from "@/utils/index";
import { ElNotification } from 'element-plus'
import qs from 'qs'
import router from "@/router"
import { close, start } from '@/utils/nporgress'
const request = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_URL,
    timeout: 1000 * 12,
    withCredentials: false
});

request.interceptors.request.use(
    config => {
        config.headers["Content-Type"] = "application/json; charset=UTF-8";
        config.headers['X-TRACE-ID']=guid();
        config.headers['X-CLIENT-ID']=import.meta.env.VITE_APP_BASE_CLIENT_ID;
        config.headers['X-CLIENT-UA']='web||1.0.0|||';
        config.headers['X-USER-INFO']='eyJ1c2VySWQiOjExNywidXNlck5hbWUiOiLpmL/mlq/pob8ifQ==';
        if (config.headers.isJwt) {
            const token = "";
            if (token) {
                config.headers['X-ACCESS-TOKEN']='bearer '+token;
                config.headers.Authorization ='bearer '+token;
            }
        }
        config.transformRequest=(data:any)=>{
            data = JSON.stringify(data)
            return data;
        }
        start();
        return config;
    },
    error => {
        Promise.reject(error);
    }
)
// 在请求之前对data传参进行格式转换
request.interceptors.response.use(
     response => {
        close();
        const result = response.data;
        if (result.code === 200) {
            return Promise.resolve(result);
        }else{
            errorHandle(result);
            return Promise.reject(result);
        }
    },
    error => {
        close();
        console.log('错误回调', error)
        // 判断请求异常信息中是否含有超时timeout字符串
        if (error.message.includes('timeout')) {
            ElNotification({
                duration:3000,
                title: '提示',
                message: '网络超时！',
                type: 'error',
            });
        }
        if (error.message.includes('Network Error')) {
            ElNotification({
                duration:3000,
                title: '提示',
                message: '服务端未启动，或网络连接错误！',
                type: 'error',
            });
        }
        if (error.message.includes('Request failed with status code 401')) {
            ElNotification({
                duration:3000,
                title: '提示',
                message: '没有访问权限，需要进行身份认证！',
                type: 'error',
            });
        }
        return Promise.reject(error)
    }
);
    /**
    * http握手错误
    * @param result 响应回调,根据不同响应进行不同操作
    */
function errorHandle(result: any) {

    switch (result.code) {
        case 50011:
            setTimeout(()=>{
                router.push({
                    path: '/login',
                    query: {
                        T:new Date().getTime()
                    }
                });
            },1500)
            ElNotification({
                duration:3000,
                title: '提示',
                message: result.msg,
                type: 'warning',
            });
        break;
        case 50010:
            setTimeout(()=>{
                router.push({
                    path: '/login',
                    query: {
                        T:new Date().getTime()
                    }
                });
            },1500)
            ElNotification({
                duration:3000,
                title: '提示',
                message: result.msg,
                type: 'warning',
            });
            break;
        case 50012:
            setTimeout(()=>{
                router.push({
                    path: '/login',
                    query: {
                        T:new Date().getTime()
                    }
                });
            },1500)
            ElNotification({
                duration:3000,
                title: '提示',
                message: result.msg,
                type: 'warning',
            });
            break;
        case 403:
        break;
        default:
            ElNotification({
                duration:3000,
                title: '提示',
                message: '异常错误！',
                type: 'warning',
            });
    }
}

/**
 * get请求
 * @param params 参数
 * @param jwt  是否token校验
 * @param url  接口
 */
 export const  getData = (url: string,params:any,isJwt:boolean) => {
    const headers={isJwt: isJwt};
    return new Promise((resolve, reject) => {
        request.get(url,{
            headers: headers,
            params: params
        }).then((response:any)=>{
            resolve(response);
        }).catch((error:any)=>{
            reject(error.msg);
        })
    });
}

/**
 * post请求
 * @param params 参数
 * @param jwt  是否token校验
 * @param url   接口
 */
export const  postData = (url: string,params: any,isJwt:boolean) => {
    const headers={isJwt: isJwt};
    return new Promise((resolve, reject) => {
        request.post(url, params, {
            headers: headers,
          }).then((response:any) => {
            resolve(response);
          }).catch((error:any) => {
            reject(error.msg);
          });
    });
}
